import { NextResponse } from "next/server"
import prisma from "@/lib/prisma"
import { getUserFromRequest } from "@/lib/auth/jwt"
import { NextRequest } from "next/server"

export async function POST(req: NextRequest) {
  try {
    // 验证用户身份
    const user = getUserFromRequest(req)
    
    if (!user) {
      return NextResponse.json(
        {
          success: false,
          error: "未授权访问",
        },
        { status: 401 }
      )
    }
    
    const { recipe } = await req.json()
    
    // 验证请求数据
    if (!recipe) {
      return NextResponse.json(
        {
          success: false,
          error: "缺少必要参数",
        },
        { status: 400 }
      )
    }
    
    // 保存配方到数据库
    const savedRecipe = await prisma.recipe.create({
      data: {
        nameEn: recipe.nameEn,
        nameZh: recipe.nameZh,
        category: recipe.category || "自定义",
        ingredients: recipe.ingredients,
        method: recipe.method,
        userId: user.userId
      }
    })
    
    return NextResponse.json({
      success: true,
      message: "配方已保存到酒柜",
      recipeId: savedRecipe.id
    })
    
  } catch (error) {
    console.error("Save Recipe API Error:", error)
    return NextResponse.json(
      {
        success: false,
        error: "保存配方失败",
      },
      { status: 500 }
    )
  }
} 